﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Net.Sockets;

using LuckyBingoRcon.Commands.Events;
using LuckyBingoRcon.Matches;
using LuckyBingoRcon.Messages;
using LuckyBingoRcon.Players;

namespace LuckyBingoRcon.Commands
{
	public class TeamStatusCommand : Command
	{
		public EventHandler<TeamStatusCommandEventArgs> OnResponse;
        
		public TeamStatusCommand()
		{
			base.commandText = "teamstatus";
            base.args = null;
		}

		protected override void CommandOnResponse(string response)
		{
			List<Players.Player> list = new List<Players.Player>();
			Map map = null;
			StringReader sr = new StringReader(response);
			bool foundPlayers = false;

			try
			{
				while (sr.Peek() > -1)
				{
					string ln = sr.ReadLine().Trim();
                    if (ln.StartsWith("map:"))// && mapLookup != null) // This should always be set, so no need to check
					{
                        ln = ln.Replace("map:", "").Trim();
						string prettyName = MapLookup.GetPrettyName(ln);
						map = new Map(ln, prettyName, mapLookup.GetAbbreviation(ln));
						continue;
					}
					else if (!foundPlayers && ln.StartsWith("---") && ln.Contains("------"))            // Heli: Player list is preempted by --- line
					{
						foundPlayers = true;
						continue;
					}
					else if (foundPlayers)
					{
						if (ln.StartsWith("\0"))
							break;

						Player player = new Players.Player();
						player = Player.FromUglyString(ln);
						if (player != null)
							list.Add(player);
					}
				}

				if (OnResponse != null)
				{
					TeamStatusCommandEventArgs e = new TeamStatusCommandEventArgs();
					e.RawResponse = response;
					e.Players = list;
					e.CurrentMap = map;
					OnResponse(this, e);
				}
			}
			catch (Exception error)
			{
				if (OnResponse != null)
				{
					TeamStatusCommandEventArgs e = new TeamStatusCommandEventArgs();
					e.Error = error;
					e.RawResponse = response;
					e.Players = list;
					e.CurrentMap = map;
					OnResponse(this, e);
				}
			}

			sr.Close();
		}

        public override string ToString()
        {
            if (base.commandText.Contains("setadmindvar"))   // Is a set command
                return "Set\tPlayer Info\t=\t" + base.args.ToString();
            else
                return "Get\tPlayer Info";
        }
	}
}
